package net.maku.framework.common.config;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;
import java.util.concurrent.CompletableFuture;

@Slf4j
@Data
@Configuration
public class MqttConsumerConfig implements ApplicationContextAware {
    @Value("${device.center.mqtt.consumer.username}")
    private String username;

    @Value("${device.center.mqtt.consumer.password}")
    private String password;

    @Value("${device.center.mqtt.consumer.url}")
    private String hostUrl;

    @Value("${device.center.mqtt.consumer.client.id}")
    private String clientId;

    @Value("${device.center.mqtt.consumer.default.topic}")
    private String defaultTopic;

    @Value("${device.center.mqtt.consumer.default.qos}")
    String defaultQos;

    /**
     * 客户端对象
     */
    private MqttClient client;

    /**
     * 回调对象
     */
    private MqttConsumerCallBack mqttConsumerCallBack;

    /**
     * 客户端连接服务端
     *
     * @param
     * @return void
     */
    public void connect(MqttConsumerCallBack mqttConsumerCallBack) {
        try {
            this.mqttConsumerCallBack = mqttConsumerCallBack == null ? new MqttConsumerCallBack() : mqttConsumerCallBack;
            //创建MQTT客户端对象
            client = new MqttClient(hostUrl, clientId, new MemoryPersistence());
            //连接设置
            MqttConnectOptions options = new MqttConnectOptions();
            //是否清空session，设置为false表示服务器会保留客户端的连接记录，客户端重连之后能获取到服务器在客户端断开连接期间推送的消息
            //设置为true表示每次连接到服务端都是以新的身份
            options.setCleanSession(true);
            //设置连接用户名
            options.setUserName(username);
            //设置连接密码
            options.setPassword(password.toCharArray());
            //设置超时时间，单位为秒
            options.setConnectionTimeout(100);
            //设置心跳时间 单位为秒，表示服务器每隔1.5*20秒的时间向客户端发送心跳判断客户端是否在线
            options.setKeepAliveInterval(20);
            //设置遗嘱消息的话题，若客户端和服务器之间的连接意外断开，服务器将发布客户端的遗嘱信息
            options.setWill("willTopic", (clientId + "与服务器断开连接").getBytes(), 0, false);
            log.info("==>Mqtt订阅端参数:{}", toString());
            //设置回调
            client.setCallback(this.mqttConsumerCallBack);
            client.connect(options);
            subscribe();
            log.info("==>MQTT 订阅端连接成功！");
        } catch (MqttException e) {
            log.error("==>MQTT 订阅端启动失败:{}", e.getMessage());
            reConnect();
        }
    }

    /**
     * 客户端连接服务端
     *
     * @param
     * @return void
     */
    public void connect() {
        connect(new MqttConsumerCallBack());
    }

    /**
     * 断开连接
     *
     * @param
     * @return void
     */
    public void disConnect() {
        try {
            client.disconnect();
        } catch (MqttException e) {
            log.error("==>MQTT 订阅端断开失败:{}", e.getMessage());
        }
    }


    /**
     * 重新连接
     *
     * @param
     * @return void
     */
    public void reConnect() {
        CompletableFuture.supplyAsync(() -> {
            while (true) {
                try {
                    if (client == null) {
                        connect(mqttConsumerCallBack);
                    } else if (!client.isConnected()) {
                        client.reconnect();
                    } else {
                        subscribe();
                        log.info("==》MQTT订阅端重连成功！");
                        break;
                    }
                    log.info("==》MQTT订阅端重连失败，稍后重试...");
                    Thread.sleep(10000l);
                } catch (MqttException | InterruptedException e) {
                    log.error("==>MQTT 订阅端重试错误:{}", e.getMessage());
                }
            }
            return null;
        });
    }

    /**
     * 订阅主题
     *
     * @param topic
     * @param qos
     * @return void
     */
    public void subscribe(String topic, int qos) {
        try {
            client.subscribe(topic, qos);
        } catch (MqttException e) {
            log.error("==>MQTT 订阅端订阅错误:{}", e.getMessage());
        }
    }


    /**
     * 订阅主题
     */
    public void subscribe() {
        try {
            //订阅主题
            //消息等级，和主题数组一一对应，服务端将按照指定等级给订阅了主题的客户端推送消息
            int[] qos = Arrays.stream(defaultQos.split(",")).mapToInt(Integer::parseInt).toArray();
            //主题
            String[] topics = defaultTopic.split(",");
            //订阅主题
            client.subscribe(topics, qos);
        } catch (MqttException e) {
            log.error("==>MQTT 订阅端订阅错误:{}", e.getMessage());
        }
    }


    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public static MqttConsumerConfig getInstant() {
        return applicationContext.getBean(MqttConsumerConfig.class);
    }
}
